<?php

namespace App\Models;

use App\Utils\TianZhenLan;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Card extends Model
{
    use HasFactory;

    public $guarded = [];

    public function companyinfo() {
        return $this->hasOne(Company::class, 'id', 'company');
    }
    public function goodsinfo() {
        return $this->hasOne(Goods::class, 'id', 'goods');
    }

    public function cityinfo() {
        return $this->hasOne(City::class, 'id', 'city_id');
    }

    public static function get_valid_card($company, $cityId, $goods, $store = null, $product_code = null, $book_datetime = null, $mobile = null, $beginId=0) {
        $cityInfo   = CompanyCity::where('company', $company)->where('city_id', $cityId)->first();
        $cityType   = $cityInfo->type;
        $card = self::whereNull('use_at')->where('company', $company)
            ->where(function($db) use ($cityType) {
              $db->where('city_type', '')->orWhere('city_type', $cityType);
            })->where(function($db) use ($cityId) {
                return $db->where('city_id', 0)->orWhere('city_id', $cityId);
            })->where(function($db) use ($goods) {
                return $db->where('goods', 0)->orWhere('goods', $goods);
            })->where('id', '>', $beginId)->first();

        // 对卡券进行有效验证
        if ($card && $company == Company::TZL) {
            if ($book_datetime) {
                $book_datetime = substr($book_datetime, 0, 16);
            }
            $res = TianZhenLan::get_card($card->code, $store, $product_code, $book_datetime, $mobile);
            if ($res->voucher_status != '1') {
                // 失效本卡
                // $card->use_at = datetime();
                // $card->order_id = 0;
                // $card->note = $
                // $card->save();
                return self::get_valid_card($company, $cityId, $goods, $store, $product_code, $book_datetime, $mobile, $card->id);
            }
        }

        return $card;
    }
}
